package top.loonglove.newindexserver.config.security.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import top.loonglove.newindexserver.entity.Account;
import top.loonglove.newindexserver.service.common.AccountService;
import top.loonglove.newindexserver.util.Status;

/**
 * @author : xgl
 * @version : 0.0.1
 * @date :2020/11/28 1:51
 */
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {

    private final AccountService accountService;

    @Autowired
    public UserAuthenticationProvider(AccountService accountService) {
        this.accountService = accountService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取表单输入中返回的用户名
        String userName = (String) authentication.getPrincipal();
        // 获取表单中输入的密码
        String password = (String) authentication.getCredentials();
        // 查询用户是否存在
        Account user = (Account) accountService.loadUserByUsername(userName);
        if (user == null) {
            throw new UsernameNotFoundException(userName );
        }
        // 我们还要判断密码是否正确，这里我们的密码使用BCryptPasswordEncoder进行加密的
        if (!new BCryptPasswordEncoder().matches(password, user.getPassword())) {
            throw new BadCredentialsException(userName );
        }
        if (user.isDel()) {
            throw new AccountStatusException(userName ) {
            };
        }
        // 还可以加一些其他信息的判断，比如用户账号已停用等判断
        if (!user.getStatus().equals(Status.ENABLE)) {
            throw new AccountStatusException(userName + "被" ) {
            };
        }
        // 进行登录
        return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
